import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';
import { Router, ActivatedRoute } from '@angular/router';
import { PageModelService } from 'src/app/service/page-model.service';
import { Subject, Subscription } from 'rxjs';
import { debounceTime, throttleTime } from "rxjs/operators";
import { DragulaService } from 'ng2-dragula';
@Component({
  selector: 'app-page-editor-detail',
  templateUrl: './page-editor-detail.component.html',
  styleUrls: ['./page-editor-detail.component.less']
})
export class PageEditorDetailComponent implements OnInit {
  @Output() config = new EventEmitter();
  pageModel = {
    id: 0,
    model: {
      els: [],
      background: {
        backgroundColor: '#fff',
        backgroundImage: '',
        select: 1
      },
      document: {
        title: ''
      }
    },
    modelName: "",
    type: 0,
    userId: 0,
  }
  isVisible = false
  isLoad = false
  tabsIndex = 0
  selectEl = null
  constructor(private dragulaService: DragulaService, private router: Router, private nzModalService: NzModalService, private activatedRoute: ActivatedRoute, private pageModelService: PageModelService) { }
  id = this.activatedRoute.snapshot.params.id
  selectElIndex = null
  tools = [
    { name: '标题组件', type: 'title', icon: '/assets/images/page-editor/icon1.png' },
    { name: 'VR直播播放器组件', type: 'player', icon: '/assets/images/page-editor/icon2.png' },
    { name: '直播间列表组件', type: 'roomList', icon: '/assets/images/page-editor/icon3.png' },
    { name: '广告组件', type: 'advert', icon: '/assets/images/page-editor/icon4.png' },
    { name: '静态内容组件', type: 'static', icon: '/assets/images/page-editor/icon5.png' },
    { name: '汇集平台', type: 'collectplatform', icon: '/assets/images/page-editor/icon9.png' },
    { name: '弹幕列表组件', type: 'danmuList', icon: '/assets/images/page-editor/icon6.png' },
    { name: '弹幕发送组件', type: 'danmu', icon: '/assets/images/page-editor/icon7.png' },
  ]
  subs = new Subscription();
  public dataStream: Subject<null> = new Subject<null>();
  ngOnInit(): void {
    this.pageModelService.findOne(this.id).subscribe(res => {
      this.pageModel = {
        id: res["data"].id,
        model: res["data"].model ? JSON.parse(res["data"].model) : {
          els: [],
          background: {
            backgroundColor: '',
            backgroundImage: '',
            select: 1
          }, document: {
            title: ''
          }
        },
        modelName: res["data"].modelName,
        type: res["data"].type,
        userId: res["data"].userId,
      }
      this.isLoad = true
      this.selectElIndex = 'background'
    })
    this.dataStream
      .pipe(debounceTime(500)).subscribe(() => {
        this.pageModelService.update(
          { ...this.pageModel, model: JSON.stringify(this.pageModel.model) }
          , this.id).subscribe(res => { })
      });
    this.dragulaDrag()

  }
  remove() {
    this.nzModalService.confirm(
      {
        nzTitle: "确定要删除这个模版码？",
        nzOnOk: () => {
          this.pageModelService.remove(this.id).subscribe(() => {
            this.router.navigate(['/main/page-editor'])
          })
        }
      })
  }
  dragulaDrag() {
    this.subs.add(this.dragulaService.dropModel()
      .subscribe(({ item, sourceModel, targetModel, target, targetIndex }) => {
        if (item.action == 'copy' && item.type == 'danmu' && this.haveEl('danmu')) {
          this.nzModalService.warning({
            nzTitle: "一个页面只能有一个弹幕组件"
          })
          return
        }
        if (item.action == 'copy' && item.type == 'danmuList' && this.haveEl('danmuList')) {
          this.nzModalService.warning({
            nzTitle: "一个页面只能有一个弹幕列表"
          })
          return
        }
        if (item.action == 'copy' && item.type == 'player' && this.haveEl('player')) {
          this.nzModalService.warning({
            nzTitle: "一个页面只能有一个播放器"
          })
          return
        }
        if (target.classList[0] == 'tab-content') {
          if (item.type == 'player') {
            this.nzModalService.warning({
              nzTitle: "播放器不能插入标签页"
            })
            return
          }

          //是拖入标签页的  
          let tabs = null
          for (let item of this.pageModel.model.els) {
            if (item.type == 'tabs') {
              tabs = item
              break
            }
          }
          delete item.action
          tabs.tabs[this.tabsIndex].data = this.deepCopy(targetModel)

        } else {
          delete item.action
          this.pageModel.model.els = this.deepCopy(targetModel)
          this.save()
        }
      })
    )

    this.dragulaService.createGroup('PERSON', {
      copy: (el, source) => {
        return source.id === 'left';
      },
      copyItem: (source) => {
        switch (source.type) {
          case 'title':
            return {
              type: 'title',
              text: '',
              color: '#333',
              textAlign: 'center',
              backgroundColor: '#fff',
              action: 'copy'
            }
          case 'player':
            return {
              type: 'player',
              weather: true,
              numberOfPeople: true,
              action: 'copy'
            }
          case 'roomList':
            return {
              type: 'roomList',
              shield: [],
              action: 'copy'
            }
          case 'advert':
            return {
              type: 'advert',
              advertList: [],
              action: 'copy'
            }
          case 'static':
            return {
              type: 'static',
              text: "",
              action: 'copy'
            }
          case 'danmuList':
            return {
              type: 'danmuList',
              action: 'copy'
            }
          case 'danmu':
            return {
              type: 'danmu',
              action: 'copy'
            }
          case 'collectplatform':
            return {
              type: 'collectplatform',
              action: 'copy'
            }

        }
      },
      accepts: (el, target, source, sibling) => {
        if (source.id == 'left') {
          return true
        }
        else {
          return target.id !== 'tab-content' && el.id != 'danmu-send';
        }

      },
    });
    this.dragulaService.createGroup('TABS', {
      copy: (el, source) => {
        return source.id === 'left';
      },
      copyItem: (source) => {
        switch (source.type) {
          case 'title':
            return {
              type: 'title',
              text: '',
              color: '#333',
              textAlign: 'center',
              backgroundColor: '#fff',
              action: 'copy'
            }
          case 'player':
            return {
              type: 'player',
              weather: true,
              numberOfPeople: true,
              action: 'copy'
            }
          case 'roomList':
            return {
              type: 'roomList',
              shield: [],
              action: 'copy'
            }
          case 'advert':
            return {
              type: 'advert',
              advertList: [],
              action: 'copy'
            }
          case 'static':
            return {
              type: 'static',
              text: "",
              action: 'copy'
            }
          case 'danmuList':
            return {
              type: 'danmuList',
              action: 'copy'
            }
          case 'danmu':
            return {
              type: 'danmu',
              action: 'copy'
            }
          case 'collectplatform':
            return {
              type: 'collectplatform',
              action: 'copy'
            }
        }
      },
      accepts: (el, target, source, sibling) => {
        return target.id !== 'left' && el.id != 'danmu-send';
      },
    });
  }
  select(e: Event, item, index) {
    e.stopPropagation()
    this.selectEl = item
    this.selectElIndex = index
  }
  haveEl(type) {
    for (let item of this.pageModel.model.els) {
      if (item.type == 'tabs') {
        for (let item2 of item.tabs) {
          for (let item3 of item2.data) {
            if (item3.type == type) {
              return true
            }
          }
        }
      }
      if (item.type == type) {
        return true
      }
    }
    return false
  }
  get background() {
    if (this.pageModel.model.background.select == 0) {
      return {
        backgroundImage: 'url(' + this.pageModel.model.background.backgroundImage + ')',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        backgroundColor: 'unset'
      }
    } else {
      return {
        backgroundColor: this.pageModel.model.background.backgroundColor
      }
    }
  }
  removeEl() {
    if (typeof this.selectElIndex == 'string') {
      let [i, j] = this.selectElIndex.split('-')
      this.pageModel.model.els[+i].tabs[this.tabsIndex].data.splice(+j, 1)
    } else {
      this.pageModel.model.els.splice(this.selectElIndex, 1)
    }
    this.selectElIndex = null
    this.save()
  }
  save() {
    this.dataStream.next();
  }
  deepCopy(source) {
    if (!this.isObject(source)) return source;
    let target = Array.isArray(source) ? [] : {}
    for (let k in source) {
      if (source.hasOwnProperty(k)) {
        if (typeof source[k] === 'object') {
          target[k] = this.deepCopy(source[k])
        } else {
          target[k] = source[k]
        }
      }
    }
    return target
  }

  isObject(obj) {
    return typeof obj === 'object' && obj !== null
  }
  copyPage() {
    this.nzModalService.confirm({
      nzOnOk: () => {
        this.pageModelService.create({
          modelName: this.pageModel.modelName + '副本',
          type: this.pageModel.type,
          model: JSON.stringify(this.pageModel.model)
        }).subscribe(res => {
          this.nzModalService.success({
            nzTitle: "创建成功"
          })
        })
      },
      nzTitle: "确定要创建副本吗"
    })
  }
  get haveDanmuSend() {
    for (let item of this.pageModel.model.els) {
      if (item.type == 'danmu')
        return true
    }
    return false
  }
  ngOnDestroy() {
    this.subs.unsubscribe();
    this.dragulaService.destroy("PERSON");
    this.dragulaService.destroy("TABS");
  }
}

